package com.example.socket.client;
 
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.ExecutionException;
 
/**
 * AIO 客户端
 * 应用程序异步非阻塞
 *
 * @author lanx
 * @date 2022/3/20
 */
public class Client implements Runnable {
 
    //客户端通道
    private AsynchronousSocketChannel asc;
 
    public Client() {
        try {
            //打开客户端通道
            asc = AsynchronousSocketChannel.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 连接服务端
     */
    private void connect() {
        asc.connect(new InetSocketAddress("127.0.0.1", 9000));
    }
 
    /**
     * 写入数据
     *
     * @param request
     */
    private void write(String request) {
        try {
            //写入数据
            asc.write(ByteBuffer.wrap(request.getBytes())).get();
            read();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
 
    /**
     * 读取数据
     */
    private void read() {
        ByteBuffer buf = ByteBuffer.allocate(1024);
        try {
            //读取数据到缓冲区
            asc.read(buf).get();
            //缓冲区数据复位
            buf.flip();
            //根据缓冲区可用长度初始化byte数据
            byte[] respByte = new byte[buf.remaining()];
            //读取缓冲区数据到respByte
            buf.get(respByte);
            //打印读取到的数据
            System.out.println("读取服务端返回数据:" + new String(respByte, "utf-8").trim());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    @Override
    public void run() {
        while (true) {
 
        }
    }
 
    public static void main(String[] args) throws InterruptedException {
 
        Client c1 = new Client();
        c1.connect();
        Client c2 = new Client();
        c2.connect();
        Client c3 = new Client();
        c3.connect();
 
        new Thread(c1, "c1").start();
        new Thread(c2, "c2").start();
        new Thread(c3, "c3").start();
 
        Thread.sleep(1000);
        c1.write("c1 data");
        c2.write("c2 data");
        c3.write("c3 data");
    }
}